package com.zsh.myserver.core.hack;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * Copyright (C), 2020-2020
 * Author: Zhoushaohua
 * Date: 2020/4/11 21:40
 * Description: 根据目录结构自动生成路由前缀
 */
public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {

    @Value("${myserver.api-package}")
    private String apiPackagePath;

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
        if (mappingInfo != null) {
            //获取到路由的前缀
            String preFix = getPreFix(handlerType);
            return RequestMappingInfo.paths(preFix).build().combine(mappingInfo);
        }
        return mappingInfo;
    }

    /**
     * 获取前缀，目标controller所在的目录结构
     *
     * @param handlerType
     * @return
     */
    private String getPreFix(Class<?> handlerType) {
        String packageName = handlerType.getPackage().getName();
        String dotPath = packageName.replaceAll(this.apiPackagePath, "");
        return dotPath.replace(".", "/");
    }
}
